﻿using CarAppClient.Consts;
using CarAppClient.Controls.MessageUsercontrols;
using CarAppClient.Extension;
using CarAppClient.Helpers;
using CarAppClient.ViewModels;
using CarAppClient.Views.CarType.Views;
using CarAppDto.CarType.CarTypeDtos;
using CarAppDto.CarType.CarDtos;
using D.UtilCore.Dtos;
using CarAppDto.CarType.AreaDtos;
using CarAppClient.Views.CarType.Views.CarType;
using System.Collections.ObjectModel;
using CarAppClient.Views.Country;
using CarAppDto.CarType.CountryDtos;
using CarAppDto.CarType.BrandDtos;
using CarAppClient.Views.CarType.Views.Brand;
using CarAppDto.CarType.VehicleSeriesDtos;
using CarAppClient.Views.CarType.Views.VehicleSeries;
using DelegateCommand = D.WPF.MVVM.EventUtil.DelegateCommand;
using CarAppClient.Views.CarParts.ViewModels.CarParts;
using CarAppDto.CarParts.CarPartsDtos;
using SqlSugar;
using CarAppClient.Views.CarParts;
using System.Linq;
using CarAppDto.Common;
using D.UtilSqlsugarOrm;
using System.Drawing.Printing;

namespace CarAppClient.Views.CarType.ViewModels.CarType
{
    public class CarTypeModifyViewModel : BaseModifyViewModel<Page_CarType_Modify>
    {      
        #region 加载页面数据

        public CarTypeModifyViewModel(Page_CarType_Modify owner, string? id, ViewStatus? viewStatus) : base(owner, id, viewStatus)
        {
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="repCarType"></param>
        protected async override void LoadData()
        {
            if (!string.IsNullOrEmpty(Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<RepCarType>.GetAsync($"{ApiUrl.GetCarType}/{Id}");

                //  判断结果
                if (res.Code == StatusCodeEnum.Waring)
                {
                    MsgUtil.Error(res.ErrorMsg);
                }
                else if (res.Code == StatusCodeEnum.Error)
                {
                    MsgUtil.Error("服务器异常");
                }
                else
                {
                    // 绑定数据源到UI 
                    if (res.Data != null)
                    {
                      
                        Name = res.Data.Name;
                        Code = res.Data.Code;                      
                        EnglishName = res.Data.EnglishName;
                        ModelYearCode=res.Data.ModelYearCode;
                        CatalogNo=res.Data.CatalogNo;
                        MarketingTime = res.Data.MarketingTime;
                        DownTime=res.Data.DownTime;

                        var resArea = await HttpHelper<RepArea>.GetAsync($"{ApiUrl.GetArea}/{res.Data.SaleAreaId}");
                        repArea = resArea.Data;
                        SaleArea = repArea?.Name;

                        var resCountry = await HttpHelper<RepCountry>.GetAsync($"{ApiUrl.GetCountry}/{res.Data.ManufacturingCountryId}");
                        repCountry = resCountry.Data;
                        ManufacturingCountry = repCountry?.Name;

                        var resBrand = await HttpHelper<RepBrand>.GetAsync($"{ApiUrl.GetBrand}/{res.Data.BrandId}");
                        repBrand = resBrand.Data;
                        Brand = repBrand?.Name;

                        var resVehicleSeries = await HttpHelper<RepVehicleSeries>.GetAsync($"{ApiUrl.GetVehicleSeries}/{res.Data.VehicleSeriesId}");
                        repVehicleSeries = resVehicleSeries.Data;
                        VehicleSeries = repVehicleSeries?.Name;

                        //if(res.Data.CarPartsList!=null)
                        //RepCarPartsList.AddRange(res.Data.CarPartsList);

                        //var resCarType = await HttpHelper<RepCarType>.GetAsync($"{ApiUrl.GetCarType}/{res.Data.CarTypeId}");
                        //repCarType = resCarType.Data;
                        //CarType = repCarType?.Name;
                        List<string> delectCarPartsList = res.Data.CarPartsList.Where(a => a.State == 2).Select(a => a.Id).ToList();

                        // 生成配件列表数据
                        // 请求后端接口 
                        var resRepCarType = await HttpHelper<List<RepCarParts>>.PostAsync(ApiUrl.VehicleSeriesPagesCarPartsList, new ReqQueryCarPartsVehicleSeriesPage()
                        {
                            VehicleSeriesId = res.Data.VehicleSeriesId,
                            PageSize = 0,
                            PageNo = 0
                        });

                        if (resRepCarType != null && resRepCarType.Data != null)
                        {

                            resRepCarType.Data.ForEach(carPart => {
                                RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                                {
                                    CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                                    Name = carPart.Name,
                                    Code = carPart.Code,
                                    Id = carPart.Id,
                                    State = delectCarPartsList.Contains(carPart.Id) ? 2 : -1,
                                    Type = 1,
                                    IsSelected=false
                                });
                            });
                        }

                        List<RepCarPartsCarTypeVersion> addCarPartsList = res.Data.CarPartsList.Where(a => a.State == 0).ToList();
                        addCarPartsList.ForEach(carPart =>
                        {
                            RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                            {
                                CarPartsTypeName = carPart.CarPartsTypeName,
                                Name = carPart.Name,
                                Id = carPart.Id,
                                Code = carPart.Code,
                                State = 0,
                                Type = 2,
                                IsSelected=false
                            });
                        });
                    }
                }
            }
        }
        #endregion

        #region 新增、修改 参数

        private string? name;
        /// <summary>
        /// 名称
        /// </summary>
        public string? Name
        {
            get { return name; }
            set { name = value; RaisePropertyChanged(); }
        }

        private string? code;
        /// <summary>
        /// 编号
        /// </summary>
        public string? Code
        {
            get { return code; }
            set { code = value; RaisePropertyChanged(); }
        }

        private string? englishName;
        /// <summary>
        /// 描述
        /// </summary>
        public string? EnglishName
        {
            get { return englishName; }
            set { englishName = value; RaisePropertyChanged(); }
        }

        RepArea repArea = null;
        private string? area;
        /// <summary>
        /// 销售区域
        /// </summary>
        public string? SaleArea
        {
            get { return area; }
            set { area = value; RaisePropertyChanged(); }
        }


        RepCountry repCountry = null;
        private string? country;
        /// <summary>
        /// 制造国家
        /// </summary>
        public string? ManufacturingCountry
        {
            get { return country; }
            set { country = value; RaisePropertyChanged(); }
        }

        RepBrand repBrand = null;
        private string? brand;
        /// <summary>
        /// 品牌
        /// </summary>
        public string? Brand
        {
            get { return brand; }
            set { brand = value; RaisePropertyChanged(); }
        }

        RepVehicleSeries repVehicleSeries = null;
        private string? vehicleSeries;
        /// <summary>
        /// 品牌
        /// </summary>
        public string? VehicleSeries
        {
            get { return vehicleSeries; }
            set { vehicleSeries = value; RaisePropertyChanged(); }
        }


        public ObservableCollection<string> SaleVehicleTypeList { get; set; }=new ObservableCollection<string>() { "普通车型", "销售车型", "精准车型" };

        private string? selectedSaleVehicleType = "普通车型";
        /// <summary>
        /// 选择的车型类型
        /// </summary>
        public string? SelectedSaleVehicleType
        {
            get { return selectedSaleVehicleType; }
            set { selectedSaleVehicleType = value; RaisePropertyChanged(); }
        }

        private string? carSeriesModel;
        /// <summary>
        /// 车系型号
        /// </summary>
        public string? CarSeriesModel
        {
            get { return carSeriesModel; }
            set { carSeriesModel = value; RaisePropertyChanged(); }
        }

        private string? modelYearCode;
        /// <summary>
        /// 年代代码
        /// </summary>
        public string? ModelYearCode
        {
            get { return modelYearCode; }
            set { modelYearCode = value; RaisePropertyChanged(); }
        }

        private string? catalogNo;
        /// <summary>
        /// 目录号
        /// </summary>
        public string? CatalogNo
        {
            get { return catalogNo; }
            set { catalogNo = value; RaisePropertyChanged(); }
        }

        private DateTime? marketingTime;
        /// <summary>
        ///上市时间
        /// </summary>
        public DateTime? MarketingTime
        {
            get { return marketingTime; }
            set { marketingTime = value; RaisePropertyChanged(); }
        }

        private DateTime? downTime;
        /// <summary>
        ///停产时间
        /// </summary>
        public DateTime? DownTime
        {
            get { return downTime; }
            set { downTime = value; RaisePropertyChanged(); }
        }

        private DateTime? saleDownTime;
        /// <summary>
        ///停产时间
        /// </summary>
        public DateTime? SaleDownTime
        {
            get { return saleDownTime; }
            set { saleDownTime = value; RaisePropertyChanged(); }
        }

        ObservableCollection<RepCarPartsCarTypeVersion> repCarPartsList=new ObservableCollection<RepCarPartsCarTypeVersion>();
        public ObservableCollection<RepCarPartsCarTypeVersion> RepCarPartsList
        {
            get { return repCarPartsList; }
            set { repCarPartsList = value; RaisePropertyChanged(); }
        }
        #endregion

        #region 保存事件
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="vm"></param>
        protected override async void Submit(object? obj)
        {
            // 基础数据判断
            if (string.IsNullOrEmpty(Name))
            {
                MsgUtil.Warning("区域名称不可为空"); return;
            }
            List<CarPartsCarType> CarPartsCarTypeVersionList = new List<CarPartsCarType>();
            var deleteList = repCarPartsList.Where(a => a.Type == 1&&a.State==2);
            foreach (var item in deleteList)
            {
                CarPartsCarTypeVersionList.Add(new CarPartsCarType()
                {
                    CarPartsId = item.Id,
                    SerialNumber = -1,
                    State = 2
                });
            }

            var addList = repCarPartsList.Where(a => a.Type == 2 && a.State == 0);
            int i = 0;
            foreach (var item in addList)
            {
                i++;
                CarPartsCarTypeVersionList.Add(new CarPartsCarType()
                {
                    CarPartsId = item.Id,
                    SerialNumber = i,
                    State = 0
                });
            }
            //List<CarPartsCarType> CarParts=new List< CarPartsCarType >();
            //repCarPartsList.
            // 基础数据判断
            if (string.IsNullOrEmpty(Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<int>.PostAsync(ApiUrl.AddCarType, new ReqAddCarType()
                {
                    BrandId = repBrand?.Id,
                    VehicleSeriesId=repVehicleSeries?.Id,
                    Name = Name,
                    Code = Code,
                    EnglishName = EnglishName,
                    VehicleModel= CarSeriesModel,
                    SaleAreaId = repArea?.Id,
                    ManufacturingCountryId = repCountry?.Id,
                    ModelYearCode = ModelYearCode,
                    CatalogNo = CatalogNo,
                    MarketingTime = MarketingTime,
                    DownTime = DownTime,
                    VehicleType= ConvertSaleVehicleType(SelectedSaleVehicleType),
                    CarParts= CarPartsCarTypeVersionList,
                }); 

                //  判断结果
                MsgUtil.ShowMsg(res.Code, "新增成功", res.ErrorMsg);
            }
            else
            {
                // 请求后端接口 
                var res = await HttpHelper<int>.PutAsync($"{ApiUrl.UpdateCarType}", new ReqUpdateCarType()
                {
                    Id = Id,
                    BrandId = repBrand?.Id,
                    VehicleSeriesId = repVehicleSeries?.Id,
                    Name = Name,
                    Code = Code,
                    EnglishName = EnglishName,
                    VehicleModel = CarSeriesModel,
                    SaleAreaId = repArea?.Id,
                    ManufacturingCountryId = repCountry?.Id,
                    ModelYearCode = ModelYearCode,
                    CatalogNo = CatalogNo,
                    MarketingTime = MarketingTime,
                    DownTime = DownTime,
                    VehicleType = ConvertSaleVehicleType(SelectedSaleVehicleType),
                    CarParts = CarPartsCarTypeVersionList,
                });
                // 判断结果
                MsgUtil.ShowMsg(res.Code, "修改成功", res.ErrorMsg);
            }
            this.FromClose();
        }
        #endregion


        protected override async void Query(string? type)
        {
            if (type == "Area")
            {
                Page_Area_Query area_Query = new Page_Area_Query();
                ((AreaQueryViewModel)area_Query.DataContext).InformationRequested += Area_InformationRequested;
                area_Query.ShowDialog();
            }
            else if (type == "Country")
            {
                Page_Country_Query country_Query = new Page_Country_Query();
                ((CountryQueryViewModel)country_Query.DataContext).InformationRequested += Country_InformationRequested;
                country_Query.ShowDialog();
            }
            else if (type == "Brand")
            {
                Page_Brand_Query brand_Query = new Page_Brand_Query();
                ((BrandQueryViewModel)brand_Query.DataContext).InformationRequested += Brand_InformationRequested;
                brand_Query.ShowDialog();
            }
            else if (type == "VehicleSeries")
            {
                if(string.IsNullOrWhiteSpace(Brand))
                    MsgUtil.Warning("品牌不可为空"); 

                Page_VehicleSeries_Query brand_VehicleSeries = new Page_VehicleSeries_Query(brandId:repBrand?.Id);
                ((VehicleSeriesQueryViewModel)brand_VehicleSeries.DataContext).InformationRequested += VehicleSeries_InformationRequested;
                brand_VehicleSeries.ShowDialog();
            }

        }

        private void Area_InformationRequested(object sender, InformationEventArgs<RepArea> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repArea = e.Information;
            if (repArea?.Name != SaleArea)
            {
                repCountry = null;
                ManufacturingCountry = "";
            }
            SaleArea = repArea?.Name;

        }

        private void Country_InformationRequested(object sender, InformationEventArgs<RepCountry> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repCountry = e.Information;
            ManufacturingCountry = repCountry?.Name;
        }

        private void Brand_InformationRequested(object sender, InformationEventArgs<RepBrand> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repBrand = e.Information;
            Brand = repBrand?.Name;
        }

        private async void VehicleSeries_InformationRequested(object sender, InformationEventArgs<RepVehicleSeries> e)
        {
            // 处理从ChildViewModel传递过来的信息
            repVehicleSeries = e.Information;
            VehicleSeries= repVehicleSeries?.Name;
            // 处理从ChildViewModel传递过来的信息
            RepCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            if (!string.IsNullOrEmpty(repVehicleSeries?.Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<List<RepCarParts>>.PostAsync(ApiUrl.VehicleSeriesPagesCarPartsList, new ReqQueryCarPartsVehicleSeriesPage()
                {
                    VehicleSeriesId = repVehicleSeries?.Id,
                    PageSize = 0,
                    PageNo = 0
                });
                if (res != null && res.Data != null)
                {

                    res.Data.ForEach(carPart => {
                        RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                        {
                            CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                            Name = carPart.Name,
                            Code = carPart.Code,
                            State = -1,
                            Type = 1,
                            IsSelected=false
                        });
                    });
                }

            }
        }

        int ConvertSaleVehicleType(string status)
        { 
          switch (status)
            {
                case "普通车型": return 0;break;
                case "销售车型": return 1; break;
                case "精准车型": return 2; break;
            }
            return -1;
        }

        string ConvertSaleVehicleTypeText(int? status)
        {
            switch (status)
            {
                case 0: return "普通车型"; break;
                case 1: return "销售车型"; break;
                case 2: return "精准车型"; break;
            }
            return "";
        }

        #region 新增
        /// <summary>
        /// 新增事件
        /// </summary>
        private DelegateCommand? _addCommand;
        /// <summary>
        /// 新增事件
        /// </summary>
        public DelegateCommand AddCommand => _addCommand ?? (_addCommand = new DelegateCommand(Add));
        /// <summary>
        /// 新增
        /// </summary>
        protected void Add(object? obj)
        {
            if (string.IsNullOrWhiteSpace(VehicleSeries))
                MsgUtil.Warning("车系不可为空");
            Page_CarParts_Query brand_CarParts = new Page_CarParts_Query();
            ((CarPartsQueryViewModel)brand_CarParts.DataContext).InformationRequested += CarParts_ListInformationRequested;
            brand_CarParts.ShowDialog();
        }

        private void CarParts_ListInformationRequested(object sender, ListInformationEventArgs<RepCarParts> e)
        {
            List<string> carPartsId = RepCarPartsList.Select(a => a.Id).ToList();
            // 处理从ChildViewModel传递过来的信息
            List<RepCarParts> repCarParts = e.Information.Where(a => !carPartsId.Contains(a.Id)).ToList();
            // RepCarPartsList.AddRange(repCarParts);
            repCarParts.ForEach(carPart => {
                RepCarPartsList.Add(new RepCarPartsCarTypeVersion()
                {
                    CarPartsTypeName = carPart.VehicleSeriesCarPartsTypeEntityName,
                    Id = carPart.Id,
                    Name = carPart.Name,
                    Code = carPart.Code,
                    State = 0,
                    Type = 2,
                    IsSelected=false
                });
            });
        }


        #endregion

        #region 批量删除
        /// <summary>
        /// 批量删除事件
        /// </summary>
        private DelegateCommand? _batchDeleteCommand;
        /// <summary>
        /// 批量删除事件
        /// </summary>
        public DelegateCommand BatchDeleteCommand => _batchDeleteCommand ?? (_batchDeleteCommand = new DelegateCommand(BatchDelete));
        protected  void BatchDelete(object? obj) {
            ObservableCollection<RepCarPartsCarTypeVersion> newCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            int n = RepCarPartsList.Count;
            for (int i = 0; i < n; i++)
            {
                RepCarPartsCarTypeVersion carTypeVersion = RepCarPartsList[i];
                if (carTypeVersion.IsSelected && carTypeVersion.Type == 1)
                {
                    carTypeVersion.State = 2;
                    newCarPartsList.Add(carTypeVersion);
                }
                else
                    newCarPartsList.Add(carTypeVersion);
            }
            RepCarPartsList = newCarPartsList;
        }

        #endregion

        #region 还原
        private bool restoreBtnEnabled = true;
        public bool RestoreBtnEnabled
        {
            get { return restoreBtnEnabled; }
            set { restoreBtnEnabled = value; RaisePropertyChanged(); }
        }
        private DelegateCommand? _restoreCommand;
        public DelegateCommand RestoreCommand => _restoreCommand ?? (_restoreCommand = new DelegateCommand(Restore));
        protected void Restore(object? obj)
        {
            if (obj == null) return;
            var selectCarParts = (RepCarPartsCarTypeVersion)obj;
            ObservableCollection<RepCarPartsCarTypeVersion> newCarPartsList = new ObservableCollection<RepCarPartsCarTypeVersion>();
            int n = RepCarPartsList.Count;
            for (int i = 0; i < n; i++)
            {
                RepCarPartsCarTypeVersion carTypeVersion = RepCarPartsList[i];
                if (carTypeVersion.Id == selectCarParts.Id)
                {
                    carTypeVersion.State = null;
                }
                newCarPartsList.Add(carTypeVersion);

            }
            RepCarPartsList = newCarPartsList;
        }

        #endregion
    }
}
